package com.teacher.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.teacher.auto.JSONAuthentication;
import com.teacher.entity.CollegeMajor;
import com.teacher.entity.TClass;
import com.teacher.entity.TUser;
import com.teacher.mapper.CollegeMajorMapper;
import com.teacher.mapper.TClassMapper;
import com.teacher.mapper.TUserMapper;
import com.teacher.response.Result;
import com.teacher.utils.UpPhotoNameUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author teacher
 * @since 2022-04-11
 */
@RestController
@RequestMapping("/t-class")
public class TClassController extends JSONAuthentication {
    @Autowired
    TClassMapper tClassMapper;
    @Autowired
    TUserMapper tUserMapper;
    @Autowired
    CollegeMajorMapper collegeMajorMapper;
    @ApiOperation(value = "添加专业")
    @PostMapping("/add")
    public void addCar(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response, @RequestParam("name") String  name,@RequestParam("totalnum") int totalnum,@RequestParam("stuId") int stuid,@RequestParam("attendTime") String attendTime,@RequestParam("value") String value,@RequestParam("address") String address,@RequestParam("fen") int fen,@RequestParam("keshi") String keshi,@RequestParam("type")String type,@RequestParam("zyId") int zyId) throws Exception {
        byte[] imgbytes=   file.getBytes();
        TClass tClass=new TClass();
        tClass.setName(name);
        tClass.setTotalnum(totalnum);
        tClass.setStuId(stuid);
        tClass.setAttendTime(attendTime);
        tClass.setValue(value);
        tClass.setAddress(address);
        tClass.setFen(fen);
        tClass.setKeshi(keshi);
        tClass.setType(type);
        tClass.setZyId(zyId);
        tClass.setPicture(imgbytes);
//        byte[] bytes = file.getBytes();
//        String imageFileName = file.getOriginalFilename();
//        String fileName = UpPhotoNameUtils.getPhotoName("img", imageFileName);
//        Path path = Paths.get("D:\\自己的项目\\云教系统\\tea1\\src\\assets\\picture\\" + fileName);
//        //“C:\\框架\\D4\\d4_pc_ui\\src\\assets\\images\\img\\”为本地目录
//        Files.write(path, bytes);//写入文件
//        String avatar_url = fileName;
//        tClass.setPicture(avatar_url);
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("name",tClass.getName());
        TClass tClass1 = tClassMapper.selectOne(wrapper);
        if(tClass1!=null){
            Result error = Result.error().message("该课程已存在");
            this.WriteJSON(request, response, error);
        }else{
            if(tClassMapper.insert(tClass)>0){
                Result ok = Result.ok();
                this.WriteJSON(request, response, ok);
            }else{
                Result error = Result.error();
                this.WriteJSON(request, response, error);
            }
        }
    }

    @ApiOperation(value = "删除课程")
    @PostMapping("/del")
    public void delUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id) throws Exception {
        int i = tClassMapper.deleteById(id);
        if (i > 0) {
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }

    @ApiOperation(value = "根据id修改课程信息（不能修改课程名字，可以修改现容纳学生数量）")
    @PostMapping("/updClassValue")
    public void updClassValue(HttpServletRequest request, HttpServletResponse response, @RequestBody TClass tClass) throws Exception {

        if(tClassMapper.updateById(tClass)>0){
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        }else{
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }

    @ApiOperation(value = "查找所有课程")
    @PostMapping("/findAllUser")
    public void findById(HttpServletRequest request, HttpServletResponse response, @RequestParam("size") int size, @RequestParam("current") int current) throws Exception {
        Page<TClass> shUserPage = new Page<>(current, size);
        Page<TClass> shUserPages = tClassMapper.selectPage(shUserPage, null);
        List<TClass> records = shUserPages.getRecords();

        for (TClass a :records){
            a.setTUserTeacher(tUserMapper.selectById(a.getStuId()));
            a.setCollegeMajor(collegeMajorMapper.selectById(a.getZyId()));
        }
        int total = tClassMapper.selectCount(null);
        if (records.size() > 0) {
            Result ok = Result.ok().data("class", records).data("total", total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "查找课程根据课程名")
    @PostMapping("/findAllUserByName")
    public void findAllUserByName(HttpServletRequest request, HttpServletResponse response, @RequestParam("size") int size, @RequestParam("current") int current,@RequestParam("name") String name) throws Exception {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.like("name",name);
        Page<TClass> shUserPage = new Page<>(current, size);
        Page<TClass> shUserPages = tClassMapper.selectPage(shUserPage, wrapper);
        List<TClass> records = shUserPages.getRecords();
        for (TClass a :records){
            a.setTUserTeacher(tUserMapper.selectById(a.getStuId()));
            a.setCollegeMajor(collegeMajorMapper.selectById(a.getZyId()));
        }
        int total = tClassMapper.selectCount(wrapper);
        if (records.size() > 0) {
            Result ok = Result.ok().data("class", records).data("total", total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }

    @ApiOperation(value = "查找课程根据授课老师姓名")
    @PostMapping("/findAllUserByTeacherName")
    public void findAllUserByTeacherName(HttpServletRequest request, HttpServletResponse response, @RequestParam("size") int size, @RequestParam("current") int current,@RequestParam("name") String name) throws Exception {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("name",name);
        TUser tUser = tUserMapper.selectOne(wrapper);
        QueryWrapper wrapper1=new QueryWrapper();
        wrapper1.eq("stu_id",tUser.getId());
        Page<TClass> shUserPage = new Page<>(current, size);
        Page<TClass> shUserPages = tClassMapper.selectPage(shUserPage, wrapper1);
        List<TClass> records = shUserPages.getRecords();
        for (TClass a :records){
            a.setTUserTeacher(tUserMapper.selectById(a.getStuId()));
            a.setCollegeMajor(collegeMajorMapper.selectById(a.getZyId()));
        }
        int total = tClassMapper.selectCount(wrapper1);
        if (records.size() > 0) {
            Result ok = Result.ok().data("class", records).data("total", total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }

    @ApiOperation(value = "查找课程根据授课老师工号")
    @PostMapping("/findAllUserByTeacherUserName")
    public void findAllUserByTeacherUserName(HttpServletRequest request, HttpServletResponse response, @RequestParam("size") int size, @RequestParam("current") int current,@RequestParam("username") String name) throws Exception {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.like("username",name);
        Page<TClass> shUserPage = new Page<>(current, size);
        Page<TClass> shUserPages = tClassMapper.selectPage(shUserPage, wrapper);
        List<TClass> records = shUserPages.getRecords();
        for (TClass a :records){
            a.setTUserTeacher(tUserMapper.selectById(a.getStuId()));
            a.setCollegeMajor(collegeMajorMapper.selectById(a.getZyId()));
        }
        int total = tClassMapper.selectCount(wrapper);
        if (records.size() > 0) {
            Result ok = Result.ok().data("class", records).data("total", total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "根据id查看课程学习")
    @PostMapping("/lookClassByClassId")
    public void lookClassByClassId(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id) throws Exception {
        TClass tClass = tClassMapper.selectById(id);
        tClass.setTUserTeacher(tUserMapper.selectById(tClass.getStuId()));
        if(tClass.getZyId()!=0){
            tClass.setCollegeMajor(collegeMajorMapper.selectById(tClass.getZyId()));
        }
        if(tClass!=null){
            Result ok = Result.ok().data("tclass",tClass);
            this.WriteJSON(request, response, ok);
        }else{
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "查找所有公选课")
    @PostMapping("/lookClassByClassIdGx")
    public void lookClassByClassIdGx(HttpServletRequest request, HttpServletResponse response, @RequestParam("size") int size, @RequestParam("current") int current) throws Exception {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.like("type","公选课");
        Page<TClass> shUserPage = new Page<>(current, size);
        Page<TClass> shUserPages = tClassMapper.selectPage(shUserPage, wrapper);
        List<TClass> records = shUserPages.getRecords();
        for (TClass a :records){
            a.setTUserTeacher(tUserMapper.selectById(a.getStuId()));
            a.setCollegeMajor(collegeMajorMapper.selectById(a.getZyId()));
        }
        int total = tClassMapper.selectCount(wrapper);
        if (records.size() > 0) {
            Result ok = Result.ok().data("class", records).data("total", total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "查找所有专业课根据专业id")
    @PostMapping("/lookClassByClassIdByZyId")
    public void lookClassByClassIdByZyId(HttpServletRequest request, HttpServletResponse response, @RequestParam("size") int size, @RequestParam("current") int current,@RequestParam("zyId") int id) throws Exception {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.like("zy_id",id);
        Page<TClass> shUserPage = new Page<>(current, size);
        Page<TClass> shUserPages = tClassMapper.selectPage(shUserPage, wrapper);
        List<TClass> records = shUserPages.getRecords();
        for (TClass a :records){
            a.setTUserTeacher(tUserMapper.selectById(a.getStuId()));
            a.setCollegeMajor(collegeMajorMapper.selectById(a.getZyId()));
        }
        int total = tClassMapper.selectCount(wrapper);
        if (records.size() > 0) {
            Result ok = Result.ok().data("class", records).data("total", total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }

//获得blob数据
    public static byte[] getImgStr(String path) throws IOException {
        FileInputStream fis = new FileInputStream(path);
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        int len = 0;
        byte[] b = new byte[1024];
        while ((len = fis.read(b))!= -1){
            out.write(b,0,len);
        }

        //接收out
        byte[] array = out.toByteArray();
        fis.close();
        out.close();

        return array;
    }
    @ApiOperation(value = "根据课程id查找图片")
    @PostMapping("/bookImgLook")
    public void book_getBookImg(HttpServletRequest request,HttpServletResponse response,@RequestParam("id") int id) throws Exception{
            byte[] imgbytes= doFindBookImg(id);
            OutputStream out= response.getOutputStream();
            out.write(imgbytes);
        Result ok = Result.ok().data("img", out);
        this.WriteJSON(request, response, ok);
    }

    @Transactional(propagation= Propagation.NOT_SUPPORTED)
    public byte[] doFindBookImg(int id) {
        try {
            TClass map= tClassMapper.selectById(id);
            return   map.getPicture();
        } catch (Exception e) {
           return null;

        }
    }
}

